package basic.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 *  阻塞式NIO
 *
 * */

public class SocketBlockNIO {

    @Test
    public void client(){
        try {
            SocketChannel socketChannel =  SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
            FileChannel fileChannel  = FileChannel.open(Paths.get("demo/1.png"));
            ByteBuffer bys = ByteBuffer.allocate(1024);
            while (fileChannel.read(bys)!=-1){
                bys.flip();
                socketChannel.write(bys);
                bys.clear();
            }
            socketChannel.shutdownOutput();
            ByteBuffer bys2 =  ByteBuffer.allocate(31);

            int len = 0;
            while ((len=socketChannel.read(bys2))!=-1){
                System.out.println(new String(bys2.array(),0,len));
            }
            fileChannel.close();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void server(){

        try {
            ServerSocketChannel serverSocketChannel  =  ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(9999));
            SocketChannel socketChannel   = serverSocketChannel.accept();
            FileChannel fileChannel = FileChannel.open(Paths.get("demo/nioSocket.png"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
            ByteBuffer bys = ByteBuffer.allocate(1024);
            while (socketChannel.read(bys)!=-1){
                bys.flip();
                fileChannel.write(bys);
                bys.clear();
            }
            ByteBuffer bys2 = ByteBuffer.allocate(31);
            String  msg = "服务器接收成功";
            bys2.put(msg.getBytes());
            bys2.flip();
            socketChannel.write(bys2);
            fileChannel.close();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void test(){
        String msg = "服务器接收成功";
        ByteBuffer bys = ByteBuffer.allocate(msg.getBytes().length+10);
        bys.put(msg.getBytes());
        System.out.println(bys);

    }
}
